package com.yt.base.util.json.tree;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonTree {

	public static String generate(List<Object> paramList, String[] paramArrayOfString, Boolean paramBoolean) {
		StringBuffer sb = new StringBuffer("[");
		HashMap<String, Node> nodeMap = construction(paramList, paramArrayOfString);
		List<Node> resultList = new ArrayList<Node>();
		Collection<Node> nodeSet = nodeMap.values();
		for (Node node : nodeSet) {
			if ((node.parentId == null) || (node.parentId.equals(""))) {
				resultList.add(node);
			} else if (nodeMap.get(node.parentId) != null) {
				nodeMap.get(node.parentId).children.addChild(node);
			}
		}
		if (paramBoolean.booleanValue()){
			Collections.sort(resultList, new NodeIDComparator());
		}
		for (Node node : resultList) {
			if (paramBoolean.booleanValue()) {
				node.sortSnChildren();
			} else {
				node.sortChildren();
			}
			sb.append(node.toString()).append(",");
		}
		if (!resultList.isEmpty())
			sb.deleteCharAt(sb.length() - 1);
		sb.append("]");
		return sb.toString();
	}

	private static HashMap<String, Node> construction(List<Object> paramList, String[] paramArrayOfString) {
		HashMap<String, Node> nodeMap = new HashMap<String, Node>();
		Map map = null;
		for (Object obj : paramList) {
			map = (Map)obj;
			Node node = new Node();
			node.id = ((String) map.get("id"));
			node.text = ((String) map.get("text"));
			node.parentId = ((String) map.get("parentId"));
			node.sn = ((String) map.get("sn"));
			if ((paramArrayOfString != null) && (paramArrayOfString.length > 0))
				for (String str : paramArrayOfString) {
					HashMap localHashMap2 = new HashMap();
					localHashMap2.put("key", str);
					localHashMap2.put("value", map.get(str) == null ? "" : map.get(str));
					node.otherList.add(localHashMap2);
				}
			nodeMap.put(node.id, node);
		}
		return nodeMap;
	}
}
